<template>
  <div>
    <Dialog
      :title="title"
      :visible="visible"
      :button-text="textBtn"
      :loading="loading"
      class="single-column"
      @close="handleClose"
      @confirm="submitForm"
    >
      <el-form
        v-show="!flag"
        ref="subscribeFormRef"
        :model="subscribeForm"
        :rules="subscribeFormRules"
        label-width="100px"
      >
        <el-form-item label="顾客：" prop="customerName">
          <el-autocomplete
            v-model="subscribeForm.customerName"
            :fetch-suggestions="querySearch"
            placeholder="姓名、手机号、编号"
            clearable
            @select="handleSelect"
          />
        </el-form-item>
        <el-form-item label="项目：" prop="projectName">
          <el-select
            v-model="subscribeForm.projectName"
            value-key="id"
            class="el-select-y"
            @change="handleSelectProject"
          >
            <el-option
              v-for="item in projectNameOptions"
              :key="item.id"
              :label="item.projectName"
              :value="item"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="接待人：" prop="receiverName">
          <el-select v-model="subscribeForm.receiverName" class="el-select-y" value-key="id">
            <el-option
              v-for="item in receiverOptions"
              :key="item.id"
              :label="item.usrName"
              :value="item.usrName"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="预约时间：" prop="appointmentDate">
          <el-col>
            <el-form-item prop="appointmentDate" class="dateStyle">
              <el-date-picker
                v-model="subscribeForm.appointmentDate"
                type="date"
                value-format="yyyy-MM-dd"
                placeholder="请选择日期"
                @change="handleDate"
              />
            </el-form-item>
          </el-col>
          <el-col style="margin-top: 18px">
            <el-form-item prop="appointmentTime" class="dateStyle">
              <el-select
                v-model="subscribeForm.appointmentTime"
                placeholder="请选择时段"
                class="el-select-y"
                clearable
              >
                <el-option
                  v-for="item in cities"
                  :key="item.value"
                  :label="item.value"
                  :value="item.value"
                  :disabled="item.label === '不可预约' ? true : false"
                >
                  <span style="float: left">{{ item.value }}</span>
                  <span style="float: right; color: #8492a6; font-size: 13px">{{
                    item.label
                  }}</span>
                </el-option>
              </el-select>
            </el-form-item>
          </el-col>
        </el-form-item>
        <el-form-item label="预约备注：" prop="appointmentRemark">
          <el-input
            v-model="subscribeForm.appointmentRemark"
            type="textarea"
            :autosize="{ minRows: 3 }"
          />
        </el-form-item>
      </el-form>
      <el-form
        v-show="flag"
        ref="lookSubscribeRef"
        :model="lookSubscribeForm"
        :rules="lookSubscribeRules"
        label-width="100px"
      >
        <el-form-item label="顾客：">{{
          lookSubscribeForm.customerName
        }}</el-form-item>
        <el-form-item label="预约类型：">{{
          lookSubscribeForm.appointmentType
        }}</el-form-item>
        <el-form-item label="接待人：">{{
          lookSubscribeForm.receiverName
        }}</el-form-item>
        <el-form-item
          label="预约时间："
        >{{ lookSubscribeForm.appointmentDate }}
          {{ lookSubscribeForm.appointmentTime }}</el-form-item>
        <el-form-item
          v-if="searchForm.appointmentStatus !== '已取消'"
          label="项目分类："
        >{{ lookSubscribeForm.advisoryClassification }}</el-form-item>
        <el-form-item v-if="title !== '取消预约'" label="预约备注：">{{
          lookSubscribeForm.appointmentRemark
        }}</el-form-item>
        <el-form-item
          v-if="title !== '预约签到' && title !== '取消预约'"
          label="预约状态："
        >{{ lookSubscribeForm.appointmentStatus }}
          {{
            lookSubscribeForm.arrivalTime ? lookSubscribeForm.arrivalTime : ""
          }}
        </el-form-item>
        <el-form-item
          v-if="searchForm.appointmentStatus === '已取消'"
          label="取消原因："
        >{{ lookSubscribeForm.cancelReason }}</el-form-item>
        <el-form-item
          v-if="searchForm.appointmentStatus === '已取消'"
          label="取消备注："
        >{{ lookSubscribeForm.cancelRemark }}</el-form-item>
        <el-form-item
          v-if="title === '取消预约'"
          label="取消原因："
          :prop="title === '取消预约' ? 'cancelReason' : ''"
        >
          <dictionary-selector
            code="RESERVE_CANCAL_CODE"
            :value.sync="lookSubscribeForm.cancelReason"
            placeholder="取消原因"
          />
        </el-form-item>
        <el-form-item
          v-if="title === '取消预约'"
          label="取消备注："
          prop="cancelRemark"
        >
          <el-input
            v-model="lookSubscribeForm.cancelRemark"
            type="textarea"
            :autosize="{ minRows: 3 }"
          />
        </el-form-item>
      </el-form>
    </Dialog>
  </div>
</template>
<script>
import Dialog from "@/components/Dialog/index";
export default {
  components: {
    Dialog,
  },
  props: {
    title: {
      type: String,
      default: "",
    },
    textBtn: {
      type: String,
      default: "",
    },
    visible: {
      type: Boolean,
      default: false,
    },
    flag: {
      type: Boolean,
      default: false,
    },
  },
  data() {
    return {
      searchForm: {},
      subscribeForm: {},
      lookSubscribeForm: {},
      projectNameOptions: [],
      receiverOptions: [],
      cities: [], // 预约时段
      seleteDate: "", // 预约选择日期
      selectCustomer: {},
      selectProject: {},
      loading: false,
      subscribeFormRules: {
        customerName: [
          { required: true, message: "请输入顾客名称", trigger: ["blur", "change"] },
        ],
        intentCaseName: [
          { required: true, message: "请选择项目", trigger: "change" },
        ],
        appointmentDate: [
          { required: true, message: "请选择预约时间", trigger: "change" },
        ],
      },
      lookSubscribeRules: {
        cancelReason: [
          { required: true, message: "请选择取消原因", trigger: "change" },
        ],
      },
    };
  },
  methods: {
    addSubscribe(row, data) {
      if (row && row.id) {
        this.subscribeForm = row;
      }
      if (data) {
        this.searchForm = data;
      }
      this.loadAll();
      this.getAllByJobName();
    },
    lookBtn(row, data) {
      this.lookSubscribeForm = row;
      this.lookSubscribeForm.advisoryClassification = row.projectType;
      this.searchForm = data;
    },
    signInBtn(row, data) {
      this.lookSubscribeForm = row;
      this.lookSubscribeForm.advisoryClassification = row.projectType;
      this.searchForm = data;
    },
    cancelBtn(row, data) {
      this.lookSubscribeForm = row;
      this.lookSubscribeForm.advisoryClassification = row.projectType;
      this.searchForm = data;
    },
    querySearch(queryString, cb) {
      var restaurants = this.restaurants;
      var results = queryString
        ? restaurants.filter(this.createFilter(queryString))
        : restaurants;
      // 调用 callback 返回建议列表的数据
      cb(results);
    },
    createFilter(queryString) {
      return (restaurant) => {
        return (
          restaurant.value.toLowerCase().indexOf(queryString.toLowerCase()) ===
          0
        );
      };
    },
    handleSelect(item) {
      this.selectCustomer = {
        customerId: item.id,
        appointmentSource: item.informationSources,
        customerSex: item.sex,
      };
      Object.assign(this.subscribeForm, this.selectCustomer);
      if (item.id) {
        this.getProjectName(item.id);
      }
    },
    handleSelectProject(item) {
      this.selectProject = {
        projectId: item.projectId,
        projectName: item.projectName,
        projectNo: item.productNo,
        projectType: item.productAttributes,
      };
      Object.assign(this.subscribeForm, this.selectProject);
    },
    async loadAll() {
      const res = await this.$api["reception/subscribe/findall"]();
      if (res.code === 200) {
        res.data.map((item) => {
          item.value = item.name;
        });
        this.restaurants = res.data;
      }
    },
    async getAllByJobName() {
      const receiverData = await this.$api["reception/subscribe/getAllByJobName"]({ hospitalJobName: "主治医生" });
      if (receiverData.code === 200) {
        this.receiverOptions = receiverData.data;
      }
    },
    // 顾客已购项目
    async getProjectName(id) {
      const res = await this.$api["reception/subscribe/customerIdAllByOrderListId"]({ customerId: id });
      if (res.code === 200) {
        this.projectNameOptions = res.data;
      }
    },
    async handleDate() {
      function p(s) {
        return s < 10 ? "0" + s : s;
      }
      const myDate = new Date();
      const year = myDate.getFullYear();
      const month = myDate.getMonth() + 1;
      const day = myDate.getDate();
      const hours = myDate.getHours();
      const minutes = myDate.getMinutes();
      const dates = year + "-" + p(month) + "-" + p(day) + "-" + p(hours) + "-" + p(minutes);
      const currentDate = dates.split("-").join("");
      if (this.subscribeForm.appointmentDate) {
        // 预约时段列表
        const timeData = await this.$api["reception/subscribe/getCreateList"]({ dictionaryId: "785558903319429120" });
        if (timeData.code !== 200) return this.$message.error(timeData.message);
        timeData.data.map((item) => {
          item.value = item.name + "-" + item.content;
          const aTime = this.subscribeForm.appointmentDate + "-" + item.content;
          const bTime = aTime.split(":").join("");
          this.seleteDate = bTime.split("-").join("");
          // console.log(currentDate, '当前本地时间');
          // console.log(this.seleteDate, '选择预约时间');
          if (Number(currentDate) > Number(this.seleteDate)) {
            item.label = "不可预约";
          } else {
            item.label = "可预约";
          }
        });
        this.cities = timeData.data;
      }
    },
    async getUpdateReportData() {
      const res = await this.$api["reception/subscribe/updateReport"]({ ...this.lookSubscribeForm });
      this.$emit("update:visible", false);
      if (res.code !== 200) return this.$message.error(res.msg);
      if (this.title === "预约签到") {
        this.$message.success('预约签到成功！');
      } else {
        this.$message.success("取消预约成功！");
      }
      this.$emit("success");
    },
    submitForm() {
      if (this.title === "添加预约") {
        this.$refs.subscribeFormRef.validate(async(valid) => {
          if (
            valid &&
            this.subscribeForm.appointmentTime &&
            this.subscribeForm.appointmentDate
          ) {
            this.subscribeForm.deptName = this.$store.getters.currentUserInfo.deptUsrList[0].deptName;
            this.subscribeForm.deptId = this.searchForm.deptId;
            this.subscribeForm.appointmentType = "治疗/复查";
            this.loading = true;
            const res = await this.$api["reception/subscribe/addappointment"]({ ...this.subscribeForm });
            this.loading = false;
            if (res.code !== 200) return this.$message.error("新增预约失败！");
            this.$message.success("新增预约成功！");
            this.$emit("update:visible", false);
            this.$emit("success");
            this.$refs.subscribeFormRef.resetFields();
          } else {
            this.$message.info("必须选择预约时间！");
          }
        });
      } else if (this.title === "预约签到") {
        this.getUpdateReportData();
        this.$emit("addTriage", this.lookSubscribeForm);
      } else if (this.title === "取消预约") {
        this.$nextTick(() => {
          this.$refs.lookSubscribeRef.validate((valid) => {
            if (valid && this.lookSubscribeForm.cancelReason) {
              this.getUpdateReportData();
            } else {
              this.$message.info("请填写取消原因！");
            }
          });
        });
      } else {
        this.$emit("update:visible", false);
      }
    },
    // 关闭
    handleClose() {
      if (this.title === "添加预约") {
        this.$refs.subscribeFormRef.resetFields();
      } else {
        this.$refs.lookSubscribeRef.resetFields();
      }
      this.$emit("update:visible", false);
    },
  },
};
</script>
<style lang="scss" scoped>
.dateStyle {
  margin-bottom: 0;
}
::v-deep .el-autocomplete {
  width: 100%;
}
</style>
